package sj.controller;


import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sj.pojo.Wallet;
import sj.pojo.WalletDetails;
import sj.service.WalletDetailsService;
import sj.service.WalletService;
import sj.util.Result;

import java.math.BigDecimal;
import java.util.List;


@RestController
public class WalletDetailsController {

    @Autowired
    private WalletService walletService;

    @Autowired
    private WalletDetailsService walletDetailsService;


    @Transactional
    @PostMapping("/consumeHundred")
    public Result consumeHundred(@Param("userId") Integer userId,
                                 @RequestParam("decreaseMoney") BigDecimal decreaseMoney,
                                 @RequestParam(value = "payMethod", defaultValue = "0") String payMethod){
        //todo 判断支付方式
        if("0".equals(payMethod)){
            boolean walletResult = walletService.consumeHundred(userId, decreaseMoney);
            if(!walletResult){
                return new Result(12,"交易失败，余额不足");
            }
            Wallet wallet = walletService.getMoneyAndIdByUserId(userId);
            WalletDetails walletDetails = new WalletDetails(null,wallet.getWalletId(), wallet.getMoney(),decreaseMoney,"1", "0");
            walletDetailsService.insertWalletDetails(walletDetails);
            return new Result(200, "钱包支付成功", walletDetails);
        }else{
            return new Result(200, "银行卡支付成功");
        }
    }



    @Transactional
    @PostMapping("/againFund")
    public Result refund(Wallet wallet,
                               @RequestParam(value = "payMethod",required = false,defaultValue = "2") String payMethod){
        if("0".equals(payMethod)){
            // 退款到钱包
            walletService.refundToWallet(wallet);

            Wallet w = walletService.getMoneyAndIdByUserId(wallet.getUserId());

            WalletDetails walletDetails = new WalletDetails(null,w.getWalletId(),w.getMoney(),wallet.getMoney(), "0", "2");

            walletDetailsService.insertWalletDetails(walletDetails);

            //todo 商品库存退回

            return new Result(200, "退款到钱包成功", walletDetails);
        }else{
            return new Result(200, "退款到银行卡");
        }
    }



    @PostMapping("/walletChange")
    public Result getWalletDetailsChangeByWalletId(@Param("walletId") Integer walletId){
        List<WalletDetails> details = walletDetailsService.getWalletDetailsByWalletId(walletId);
        if(!CollectionUtils.isEmpty(details)){
            return new Result(200, "walletId = " +walletId + " 的消费流水 查询成功", details);
        }
        return new Result(200, "暂无消费记录");
    }
}
